﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Text;

using SimpleText.Framework;

public partial class ExtractorPage : SimpleTextPage 
{
	
  protected void Page_Load(object sender, EventArgs e)
  {
		InitPage();

		if (CurrentModel == null)
		{
			Response.Redirect("projects.aspx?msg=noprojectselected");
		}
	}

	protected void ContinueStep1Clicked(object sender, EventArgs e)
	{
		if (!Directory.Exists(PathTxt.Value))
		{
			Step1ErrorPlh.Visible = true;
			Step1ErrorLit.Text = "<div class=\"warning\">Invalid path specified</div>";
			return;
		}

		string[] extensions = ExtensionsTxt.Value.Split(',');
		for (int i = 0; i < extensions.Length; i++)
		{
			extensions[i] = "." + extensions[i];
		}

		List<TextGroupFoundByWizard> foundGroups = new List<TextGroupFoundByWizard>();
		foundGroups = ExtractTextsFromFiles(PathTxt.Value, extensions, foundGroups, PathTxt.Value, RegexTxt.Value);

		//persist to viewstate (we need it again in the next wizard step)
		ViewState["FoundGroups"] = foundGroups;
		ViewState["ExtractedFromPath"] = PathTxt.Value;

		StringBuilder textListSB = new StringBuilder("");
		textListSB.Append("<table class=\"grid extractorGrid\">" + "\r\n");
		foreach (TextGroupFoundByWizard foundGroup in foundGroups)
		{
			textListSB.Append(
				"<tr>" + "\r\n" +
				"	<td colspan=\"3\" class=\"groupHeader\">" + foundGroup.FileName + " (" + foundGroup.RelativePath + ")</td>" + "\r\n" +
				"</tr>" + "\r\n"
			);

			IDictionary<string, string> foundTextDefNameDict = new Dictionary<string, string>();
			if (foundGroup.TextDefinitions.Count == 0)
			{
				textListSB.Append(
						"<tr>" + "\r\n" +
						"	<td class=\"nostripe\"></td>" + "\r\n" +
						"	<td colspan=\"2\" class=\"nostripe\"><i>none</i></td>" + "\r\n" +
						"</tr>" + "\r\n"
					);
			}
			else
			{
				foreach (TextDefinitionFoundByWizard foundTextDef in foundGroup.TextDefinitions)
				{
					string definitionExists = null;
					if (!CurrentModel.TextDefinitions.ContainsKey(foundTextDef.TextDefinitionName))
					{
						definitionExists = "<i>new</i>";
					}
					string definitionIsDoublet = "";
					if (foundTextDefNameDict.ContainsKey(foundTextDef.TextDefinitionName))
					{
						definitionIsDoublet = "<i>doublet</i>";
					}
					else
					{
						foundTextDefNameDict.Add(foundTextDef.TextDefinitionName, "");
					}

					string defaultValue = foundTextDef.DefaultText;
					if (defaultValue.Length > 100)
					{
						defaultValue = defaultValue.Substring(0, 97) + "...";
					}

					textListSB.Append(
							"<tr>" + "\r\n" +
							"	<td></td>" + "\r\n" +
							"	<td><b>" + foundTextDef.TextDefinitionName + "</b> " + definitionExists + " " + definitionIsDoublet + "</td>" + "\r\n" +
							"	<td>" + Server.HtmlEncode(defaultValue) + "</td>" + "\r\n" +
							"</tr>" + "\r\n"
						);

				}
			}
		}

		string textRegExString = RegexTxt.Value;//"Txt.Get[a-z]*\\(\\\"(?<textmatch>([a-z]*))\\\"\\)";
		string path = PathTxt.Value;
		string extensionsCommaSep = ExtensionsTxt.Value;
		RegexLit.Text = Server.HtmlEncode(textRegExString);
		PathLit.Text = Server.HtmlEncode(path);
		ExtensionsLit.Text = Server.HtmlEncode(extensionsCommaSep);

		textListSB.Append("</table>" + "\r\n");
		FileLit.Text += textListSB.ToString();
		
		//settings
		LanguageSel.DataSource = CurrentModel.Languages;
		LanguageSel.DataTextField = "Name";
		LanguageSel.DataValueField = "ShortName";
		LanguageSel.Value = CurrentModel.MasterLanguageShortName;
		LanguageSel.DataBind();
		LanguageSel.Items.Insert(0, new ListItem("-", ""));

		//set interface state
		Step1Plh.Visible = false;
		Step2Plh.Visible = true;
		SuccessPlh.Visible = false;
	}


	protected void ContinueStep2Clicked(object sender, EventArgs e)
	{
		List<TextGroupFoundByWizard> foundGroups = (List<TextGroupFoundByWizard>)ViewState["FoundGroups"];
		string extractedFromPath = (string)ViewState["ExtractedFromPath"];

		string defaultLanguageShortName = LanguageSel.Value;

		foreach (TextGroupFoundByWizard foundGroup in foundGroups)
		{
			foreach (TextDefinitionFoundByWizard foundTextDef in foundGroup.TextDefinitions)
			{
				if (CurrentModel.TextDefinitions.ContainsKey(foundTextDef.TextDefinitionName))
				{
					//existing text
					//TODO: Add option to update the default text with the one extracted
				}
				else
				{
					Text newText = new Text();
					newText.Content = foundTextDef.DefaultText;
					newText.LanguageShortName = defaultLanguageShortName;
					TextDefinition newTextDef = new TextDefinition();
					newTextDef.Name = foundTextDef.TextDefinitionName;
					newTextDef.Texts[newText.LanguageShortName] = newText;
					//Comment and Source removed. They are rarely used and are very verbose
					//newTextDef.Comment = "Extracted from " + extractedFromPath + " (" + DateTime.Now.ToString() + ")";
					//newTextDef.Source = foundGroup.RelativePathAndFileName;

					CurrentModel.TextDefinitions[foundTextDef.TextDefinitionName] = newTextDef;
				}
			}
		}

		//Persist changed model
		SaveModel(CurrentModel, CurrentModel.LoadedFromXmlFilePath);
		
		//set interface state
		Step1Plh.Visible = false;
		Step2Plh.Visible = false;
		SuccessPlh.Visible = true;
	}
}
